<?php

namespace interface\v1;

/*
*宿舍管理接口类
*/

use verify;

class dormitoryAppClass extends index
{
	private const page  = 'dormitory';
	private const title = '查寝记录';
	private const table = 'dormitory_live';
	
	/*查询条件*/
	public function search()
	{
		$data   = [];
		$option = [];
		$type   = $this->post('type');
		if (empty($type) || $type == 'building') {
			$all = find(array('table' => 'dormitory', 'where' => "order by building asc", 'field' => "distinct(building) as building"));
			
			foreach ($all['array'] as $array) {
				$option[] = $array['building'];
			}
			$data['building'] = $option;
		} elseif ($type == 'floor') {
			$all = find(array('table' => 'dormitory', 'where' => "building = '" . $this->post('building') . "' order by floor asc", 'field' => "distinct(floor)"));
			foreach ($all['array'] as $array) {
				$option[] = $array['floor'];
			}
			$data['floor'] = $option;
		}
		$data['typeOption'] = explode('，', para('dormitoryType'));
		$data['timeOption'] = $this->timeOption;
		//返回
		$this->code         = 1;
		$this->resp['data'] = $data;
	}
	
	/*查寝列表页*/
	public function live_list()
	{
		//全等查询数组
		$equal = array(
			"a.stid"     => self::$stid,//员工
			"b.building" => $this->post('building'),
			"b.type"     => $this->post('dor_type'),
		);
		//初始化
		$and = '';
		if ($this->post('keyword')) {
			$and .= " and (b.room like '%" . $this->post('keyword') . "%')";
		}
		$commitTime = $this->post('commit_time');
		if (!$commitTime) {
			if ($this->post('startDate')) {
				$commitTime = $this->post('startDate');
			}
			if ($this->post('endDate')) {
				$commitTime .= empty($commitTime) ? $this->post('endDate') : ('~' . $this->post('endDate'));
			}
		}
		if ($commitTime) {
			$and .= $this->miniTimeComparison($commitTime, field: "a.recordDate");
		}
		//获取查询结果
		$where = search(array("=" => $equal)) . $and;
		$page  = $this->page(array("table" => 'dormitory_live as a join dormitory as b on a.dormitoryId = b.id', 'field' => "b.building,b.floor,b.room,b.type,a.*", "where" => $where, "order" => "a.recordDate desc,a.time desc"));
		//数据分析
		$data['result'] = [];
		foreach ($page['array'] as $array) {
			$data['result'][] = array(
				"id"          => $array['id'],//ID
				'name'        => $array['building'] . $array['floor'] . $array['room'],
				"type"        => $array['type'],
				"recordDate"  => $array['recordDate'],
				"isHealth"    => $array['isHealth'],
				"isPower"     => $array['isPower'],
				'isViolation' => $array['isViolation'],
				'text'        => $array['text'],
				'stName'      => self::findStaff($array['stid']),
				'time'        => date('m/d', strtotime($array['time'])),
			);
		}
		$data['page'] = $page['para'];
		//返回
		$this->code         = 1;
		$this->resp['data'] = $data;
	}
	
	/**
	 * 获取宿舍
	 */
	public function dormitory()
	{
		$all  = find(array('table' => 'dormitory', 'where' => "state = '启用' order by time"));
		$list = [];
		foreach ($all['array'] as $array) {
			$list[] = [
				'id'   => $array['id'],
				'name' => $array['building'] . $array['floor'] . $array['room'],
			];
		}
		$this->code         = 1;
		$this->resp['data'] = $list;
	}
	
	/*列表页*/
	public function list()
	{
		$building = $this->post('building');
		$floor    = $this->post('floor');
		$data     = [];
		$roomAll  = find(array('table' => 'dormitory', 'where' => "building = '" . $building . "' and floor = '$floor' order by room asc"));
		foreach ($roomAll['array'] as $room) {
			$livePeople     = self::total(array('table' => 'dormitory_record', 'where' => "dormitoryId = '$room[id]' and state = '入住'"));
			$people         = find(array('table' => "dormitory_record as a join staff as b on a.staffId = b.stid", 'single' => "a.dormitoryId = '$room[id]' and a.state = '入住' group by dormitoryId", 'field' => "group_concat(b.name) as name"));
			$people['name'] = $people['name'] ?? '-';
			$color          = 1;
			if ($room['state'] != '启用') {
				$color = 3;
			} elseif ($livePeople >= $room['maxPeople']) {
				$color = 2;
			}
			$data[] = [
				'id'     => $room['id'],
				'name'   => $room['room'],
				'type'   => $room['type'],
				'live'   => $room['maxPeople'] . '/' . $livePeople,
				'stName' => $people['name'],
				'state'  => $color,
			];
		}
		//返回
		$this->code                 = 1;
		$this->resp['data']['list'] = $data;
	}
	
	
	/**
	 * 编辑
	 */
	public function liveEdit()
	{
		$id         = $this->post('id') ?: self::getId();
		$field      = [
			'recordDate'  => $this->post('recordDate'),
			'dormitoryId' => $this->post('dormitoryId'),
			'isHealth'    => $this->post('isHealth'),
			'isPower'     => $this->post('isPower'),
			'isViolation' => $this->post('isViolation'),
			'text'        => $this->post('text'),
		];
		$annotation = [
			'recordDate'  => '日期',
			'dormitoryId' => '宿舍',
			'isHealth'    => '请假卫生',
			'isPower'     => '大功率电器',
			'isViolation' => '其他违规项',
		];
		$rules      = [
			'recordDate'  => 'required',
			'dormitoryId' => 'required',
			'isHealth'    => 'required',
			'isPower'     => 'required',
			'isViolation' => 'required',
		];
		// 校验是否符合规则
		$vt     = new verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$this->resp['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}
		//判断
		if (!$this->power(self::page, "edit")) {
			$this->resp['warn'] = "你没有编辑的权限";
		} else {
			$where = " id = '$id' ";
			$info  = query('dormitory_live', $where);
			if (!$info['id']) {
				$field              = array_merge($field, [
					'id'   => $id,
					'stid' => $this->control['stid'],
				]);
				$this->resp['warn'] = static::insert(["table" => 'dormitory_live', "field" => $field]);
			} else {
				$this->resp['warn'] = static::update([
					"table" => 'dormitory_live',
					"field" => $field,
					"where" => $where,
				]);
			}
			if (in_array($this->resp['warn'], ["新增成功", "更新成功"])) {
				//添加日志
				$type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				$this->resp['data']['id'] = $id;
				//返回
				$this->code = 1;
			}
		}
		resp:
	}
	
	/*详情页*/
	public function detail()
	{
		$id   = $this->post('id');
		$info = query(self::table, "id = '" . $id . "'");
		if (empty($id)) {
			$this->resp['warn'] = "ID为空";
		} elseif (empty($info['id'])) {
			$this->resp['warn'] = "未找到此" . self::title;
		} else {
			$dormitory      = query('dormitory', "id = '$info[dormitoryId]'");
			$data['result'] = [
				'id'            => $id,
				'dormitoryId'   => $info['dormitoryId'],
				'dormitoryName' => $dormitory['building'] . $dormitory['floor'] . $dormitory['room'],
				'recordDate'    => $info['recordDate'],
				'text'          => $info['text'],
				'isHealth'      => $info['isHealth'],
				'isPower'       => $info['isPower'],
				'isViolation'   => $info['isViolation'],
			];
			//返回
			$this->code         = 1;
			$this->resp['data'] = $data;
		}
	}
	
	/**
	 * 删除
	 */
	public function delete()
	{
		$id   = $this->post('id');
		$info = query(self::table, "id = '$id'");
		if (!$this->power(self::page, 'del')) {
			$this->resp['warn'] = "你没有删除的权限";
		} elseif (empty($info['id'])) {
			$this->resp['warn'] = "未找到此" . self::title;
		} elseif ($info['stid'] != self::$stid) {
			$this->resp['warn'] = "这不是你的" . self::title;
		} elseif ($info['state'] != '草稿') {
			$this->resp['warn'] = "此" . self::title . "不是草稿状态，不能删除";
		} else {
			$warn = delete(array('table' => self::table, 'where' => "id = '$id'"));
			if ($warn == '删除成功') {
				//删除audit表记录
				delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
				//删除待办事项
				delete(array("table" => "backlog", "where" => " typeId = '$id' "));
				//删除审批记录
				delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
				//删除消息提醒
				delete(array("table" => "message", "where" => " typeId = '$id' "));
				//添加记录
				$text = "{$this->control['name']}删除了一条" . self::title . "：ID【{$id}】" . '<br>';
				// 写入日志
				$this->logText(["type" => self::page, "text" => $text]);
				$this->code         = 1;
				$this->resp['warn'] = '删除成功';
			} else {
				$this->resp['warn'] = '删除失败';
			}
		}
		resp:
	}
}
